<?php
class CmsMenuModel extends ModelTree
{
    protected static $instance;
    protected $parentField = 'parent_id';
    protected $cache;

    public function CmsMenuModel()
    {
        parent::__construct();
        $this->cache = new CacheData($this->GetClassName());
    }

    public static function GetInstance()
    {
        return self::$instance ? self::$instance : self::$instance = new CmsMenuModel();
    }

    protected function LoadFields()
    {
        parent::LoadFields();
        $this->SetForeignKey('parent_id', $this->GetTableName(), 'id');
        $this->AddOneToManyRelation('cms_menu', 'parent_id');
    }

    public function Insert($item)
    {
        $this->cache->ClearAll();
        return parent::Insert($item);
    }

    public function Update($item)
    {
        $this->cache->ClearAll();
        return parent::Update($item);
    }

    public function Del($id)
    {
        $this->cache->ClearAll();
        parent::Del($id);
    }

//    protected function UpdateSortOrder(&$item)
//    {
//        if (isset($item['sort_order']))
//        {
//            $menu = $this->FindById($item['id'], 'parent_id, id');
//            $parent_id = $menu['parent_id'];
//            $menu['sort_order'] = $item['sort_order'];

//            $menus = $this->FindBy('parent_id', $parent_id, 'id, sort_order');
//            $menus = Set::ReOrder($menu, $menus, 'id', 'sort_order');
//            foreach ($menus as $m)
//            {
//                parent::Update($m);
//            }
//            unset($item['sort_order']);
//        }
//    }

    public function GetTree($parent_id)
    {
        $this->cache->SetCacheId('GetTree'.$parent_id);
        if ($this->cache->IsValid())
            return $this->cache->Render();
        else
        {
            $this->expandAll = true;
            $cond = new SqlCondition();
            $cond->AddNumber('parent_id', $parent_id);
            $this->recursiveCondition = new SqlCondition();
            $this->recursiveCondition->AddNumber('enabled', 1);
            $tree = $this->FindNodes($cond, null, 'sort_order');
            $this->cache->Save($tree);
            return $tree;
        }
    }

    public function GetChilds($parent_id, $fields = null)
    {
        return $this->FindBy('parent_id', $parent_id, $fields, 'sort_order');
    }
}
?>
